/****************************************************
          File Name:pisces_daemon.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
           Created Time: Tue 13 Jan 2015 02:39:58 PM CST
*****************************************************/

#include "header.h"
#include <sys/resource.h>

int my_daemon(void)
{
    int fd0, fd1, fd2;
    pid_t pid;
    struct rlimit lim;
    int i;

    umask(0);

    if (getrlimit(RLIMIT_NOFILE, &lim) < 0)
        return -1;

    lim.rlim_max = lim.rlim_cur + 1;

    if (setrlimit(RLIMIT_NOFILE, &lim) < 0)
        return -1;

    for (i = 0; i < lim.rlim_max; i++)
        close(i);

    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);

    /* attach file descriptors to /dev/null failed, return -1 */
    if (fd0 != 0 || fd1 != 1 || fd2 != 2)
        return -1;

    if ((pid = fork()) < 0)
        return -1;
    else if (pid != 0)
        exit(0);

    setsid();

    if ((pid = fork()) < 0)
        return -2;
    else if (pid != 0)
        exit(0);

    return 0;
}
